package com.gorkr.labuladong.data_struct.array.windows;

import org.junit.jupiter.api.Test;

import java.util.HashMap;

/**
 * @author gorkr
 * @date 2022/06/07 00:11
 **/
public class M567PermutationInString {

    public boolean checkInclusion(String s1, String s2) {

        HashMap<Character, Integer> need = new HashMap<>();
        for (Character c : s1.toCharArray()
        ) {
            need.put(c, need.getOrDefault(c, 0) + 1);
        }

        HashMap<Character, Integer> window = new HashMap<>();

        int left = 0, right = 0;
        int start = 0;
        int len = Integer.MAX_VALUE;
        int valid = 0;

        while (right < s2.length()) {
            // 将要移进窗口的字符
            char c = s2.charAt(right);
            right++;

            // 处理加入窗口的逻辑
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (window.get(c).equals(need.get(c))) {
                    valid++;
                }
            }

            while (valid == need.size()) {
                if (right - left < len) {
                    len = right - left;
                    if (len == s1.length()) {
                        return true;
                    }
                }


                char b = s2.charAt(left);
                left++;

                if (need.containsKey(b)) {
                    window.put(b, window.get(b) - 1);
                    if (window.get(b)<need.get(b)) {
                        valid--;
                    }
                }

            }


        }


        return false;
    }

    @Test
    public void test(){

//        String s1 = "ab";
        String s1 = "abc";
//        String s2 = "eidbaooo";
//        String s2 = "eidboaoo";
        String s2 = "bbbca";
        System.out.println(checkInclusion(s1, s2));
    }
}
    